
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
//
#include "esp_log.h"
#include "esp_err.h"
//
#include "unity.h"
#include "string.h"
#include <sys/stat.h>
//
#include "iot_button.h"
//
#include "main.h"



/************************************************************************
 * DEFINES
 ************************************************************************/
#define TAG_BTN             "IOT_BTN"

#define BTN_UP_PIN   12
#define BTN_M_PIN    1
#define BTN_DWN_PIN  0

//菜单状态
typedef enum
{
    MENU_EMPTY = 0, //空闲
    // MENU_BEGIN,     //进入
    MENU_SELECT,    //选择
    MENU_CONFIRM    //确认
}menu_state_t;  //TODO: 也许不需要typedef

//按键索引
typedef enum
{
    BTN_IDX_UP = 0,
    BTN_IDX_M,
    BTN_IDX_DWN,
    BTN_IDX_ALL     //按键数量
}Btn_Idx_t;

//按键信息
typedef struct
{
    uint8_t btnIdx;
    uint8_t gpioNum;
}Btn_Info_t;

static int __getBtnIndex(button_handle_t btn);
static void __btnCb_LongPressStart(void *arg, void *data);
static void __btnCb_PressDown(void *arg, void *data);
static void __btnCb_DblPressDown(void *arg, void *data);

/************************************************************************
 * VARIABLE
 ************************************************************************/
Btn_Info_t BtnInfo[BTN_IDX_ALL] = 
{
    {BTN_IDX_UP, BTN_UP_PIN},
    {BTN_IDX_M, BTN_M_PIN},
    {BTN_IDX_DWN, BTN_DWN_PIN},
};

static button_handle_t g_btns[BTN_IDX_ALL] = {0};

menu_state_t MenuState = MENU_EMPTY;  //状态初始值


/************************************************************************
 * FUNCTIONS
 ************************************************************************/


//
void Btn_init()
{
    uint8_t i;

    //设置&创建gpio按键
    button_config_t cfg = {
        .type = BUTTON_TYPE_GPIO,
        .long_press_time = CONFIG_BUTTON_LONG_PRESS_TIME_MS, //CONFIG_BUTTON_LONG_PRESS_TIME_MS=1500
        .short_press_time = CONFIG_BUTTON_SHORT_PRESS_TIME_MS, //CONFIG_BUTTON_SHORT_PRESS_TIME_MS=180
        .gpio_button_config = {
            // .gpio_num = BTN_UP,
            .active_level = 1,
        },
    };
    //
    for(i = 0; i < BTN_IDX_ALL; i++)
    {
        cfg.gpio_button_config.gpio_num = BtnInfo[i].gpioNum;
        g_btns[BtnInfo[i].btnIdx] = iot_button_create(&cfg);
    }
    
    //注册按键回调
    //
    iot_button_register_cb(g_btns[BTN_IDX_UP], BUTTON_SINGLE_CLICK, __btnCb_PressDown, NULL);
    iot_button_register_cb(g_btns[BTN_IDX_M], BUTTON_SINGLE_CLICK, __btnCb_PressDown, NULL);
    iot_button_register_cb(g_btns[BTN_IDX_DWN], BUTTON_SINGLE_CLICK, __btnCb_PressDown, NULL);
    //
    iot_button_register_cb(g_btns[BTN_IDX_M], BUTTON_LONG_PRESS_START, __btnCb_LongPressStart, NULL);
    //
    iot_button_register_cb(g_btns[BTN_IDX_M], BUTTON_DOUBLE_CLICK, __btnCb_DblPressDown, NULL);
}

//=========================== 按键转为序号
// description:
//
static int __getBtnIndex(button_handle_t btn)
{
    for (size_t i = 0; i < BTN_IDX_ALL; i++) {
        if (btn == g_btns[i]) {
            return i;
        }
    }
    return -1;
}

//=========================== 回调函数 - 短按
// description:
//
static void __btnCb_PressDown(void *arg, void *data)
{
    // TEST_ASSERT_EQUAL_HEX(BUTTON_PRESS_DOWN, iot_button_get_event(arg)); //TODO: ??? 这个为什么会触发WDT
    // ESP_LOGI(TAG_BTN, "BTN%d: BUTTON_PRESS_DOWN", __getBtnIndex((button_handle_t)arg));

    //获取按键序号
    Btn_Idx_t btn_idx = __getBtnIndex((button_handle_t)arg);
    //
    if(MenuState == MENU_EMPTY) //空闲态, 允许保存Photo
    {
        // if(btn_idx == BTN_IDX_M)
        // {
        //     Save_PhotoImg_to_File(); //保存Photo到文件

        //     // Save_GuiImg_to_File(NULL); //保存Gui到文件
        // }
    }
    else if(MenuState == MENU_SELECT) //选择态
    {
        //获取按键
        switch (btn_idx)
        {
            case BTN_IDX_UP:
                ESP_LOGI(TAG_BTN, "BTN_IDX_UP");
                if(Update_GuiImg_to_Select(-1) == 1)
                    Update_GuiImg_from_List();
                break;
            case BTN_IDX_DWN:
                ESP_LOGI(TAG_BTN, "BTN_IDX_DWN");
                if(Update_GuiImg_to_Select(1) == 1)
                    Update_GuiImg_from_List();
                break;
            
            default:
                break;
        }
    }
    else
        return;
    
}

//=========================== 回调函数 - 双击
// description:
//
static void __btnCb_DblPressDown(void *arg, void *data)
{
    TEST_ASSERT_EQUAL_HEX(BUTTON_DOUBLE_CLICK, iot_button_get_event(arg));

    Btn_Idx_t btn_idx = __getBtnIndex((button_handle_t)arg);
    ESP_LOGI(TAG_BTN, "__btnCb_DblPressDown: state is %d, BTN%d", MenuState, btn_idx);
    //
    if((MenuState == MENU_SELECT) && (btn_idx == BTN_IDX_M)) //MENU_SELECT态下允许双击删除操作
    {
        if(Delete_PhotoImg_from_SDCard() == 0) //删除Photo并刷新Gui
        {
            ESP_LOGI(TAG_BTN, "__btnCb_DblPressDown: delete ok");
        }
        else
            ESP_LOGI(TAG_BTN, "__btnCb_DblPressDown: delete failed");

        //============ old code - 待删除
        // struct stat sta;
        // char file_name[FILE_PATH_LEN_MAX];
        // 
        // //获取文件名
        // SDCard_File_GetOnePath(file_name);
        // ESP_LOGI(TAG_BTN, "try to delete %s", file_name);
        // //判断文件存在
        // if(stat(file_name, &sta) == 0)
        // {
        //     if(remove(file_name) == 0) //删除Photo
        //     {
        //         ESP_LOGI(TAG_BTN, "delete Photo ok");
        //         //重置Gui
        //         // Load_GuiImg_from_File(NULL);
        //         //刷新file list
        //         SDCard_File_ListAllNames(DEFAULT_IMG_DIR_PATH);
        //         //更新CurrentIdx
        //         if(SDCard_File_IsCurrentIdxAtTail() == 1)
        //             Update_GuiImg_to_Select(-1);
        //         //刷新Gui
        //         Update_GuiImg_from_List();
        //     }
        //     else
        //         ESP_LOGI(TAG_BTN, "delete Photo failed..");
        // }
        // else
        //     ESP_LOGI(TAG_BTN, "file not exist");
    }
    else if(MenuState == MENU_EMPTY)
    {
        if(btn_idx == BTN_IDX_M)  //空闲态, 允许保存Photo
        {
            Save_PhotoImg_to_File(); //保存Photo到文件

            // Save_GuiImg_to_File(NULL); //保存Gui到文件
        }
    }
}

//=========================== 回调函数 - 长按
// description:
//
static void __btnCb_LongPressStart(void *arg, void *data)
{
    TEST_ASSERT_EQUAL_HEX(BUTTON_LONG_PRESS_START, iot_button_get_event(arg));

    Btn_Idx_t btn_idx = __getBtnIndex((button_handle_t)arg);
    // ESP_LOGI(TAG_BTN, "BTN%d: BUTTON_LONG_PRESS_START", btn_idx);
    //
    if (btn_idx == BTN_IDX_M)
    {
        if(MenuState == MENU_EMPTY) //进入menu
        {
            ESP_LOGI(TAG_BTN, "from MENU_EMPTY to MENU_SELECT");

            //读取GUI界面
            Load_GuiImg_from_File(NULL); //默认路径为"/EPD/bk/bk.txt"
            // ESP_LOGI(TAG_BTN, "__btnCb_LongPressStart: read Gui");
            //读取文件列表
            SDCard_File_ListAllNames(DEFAULT_IMG_DIR);
            //重置CurrentIdx
            // SDCard_File_CurrentIdx_Set(0);
            //GUI放置选择块到CurrentIdx=0
            Update_GuiImg_to_Select(99); //这里会重置CurrentIdx
            //文件列表刷新GUI
            Update_GuiImg_from_List();
            
            //更新状态
            MenuState = MENU_SELECT;
        }
        else if(MenuState == MENU_SELECT)
        {
            ESP_LOGI(TAG_BTN, "from MENU_SELECT to MENU_EMPTY");

            //获取文件名并刷新界面
            Load_PhotoImg_from_File();

            //更新状态
            MenuState = MENU_EMPTY;            
        }
        else
        {
            ESP_LOGI(TAG_BTN, "__btnCb_LongPressStart: empty MenuState");
            return;
        }
    }

}





//==================// TODO: 代码备份
//
//------------ 删除test.txt, 将get.txt重命名为test.txt
    // int8_t ret;
    // const char *file_path_old = MOUNT_POINT"/EPD/get.txt";
    // const char *file_path_new = MOUNT_POINT"/EPD/test.txt";
    // struct stat sta;
    //
    // if(stat(file_path_new, &sta) == 0) //文件存在
    // {
    //     if(remove(file_path_new) == 0)
    //         ESP_LOGI(TAG_BTN, "delete test.txt ok");
    //     else
    //         ESP_LOGI(TAG_BTN, "delete test.txt failed..");
    // }
    //
    // ret = rename(file_path_old, file_path_new);
    // if(ret == 0)
    // {
    //     ESP_LOGI(TAG_BTN, "rename ok");
    // }
    // else
    // {
    //     ESP_LOGI(TAG_BTN, "rename failed");
    // }
    // ESP_LOGI(TAG_BTN, "ret=%d", ret);
//
//
//------------ SD卡中读取图像进行显示
    // if(SDCard_File_Open(file_name, FILE_MODE_READ) == ESP_OK)
    // {
    //     // uint 16_t img_val;
    //     char img_val[FILE_WRITE_BLOCK_SIZE];
    //     uint16_t tmp = 0;
    //
    //     ePaper_ResetImgIndex();
    //
    //     ESP_LOGI(TAG_BTN, "start read tmp.txt"); 
    //     while (SDCard_File_Read_Img(img_val, FILE_WRITE_BLOCK_SIZE) == ESP_OK) //应该固定读取到96行, 每行1000个字符
    //     {
    //         //设置EPD
    //         ePaper_SetImgDataByChar(img_val, strlen(img_val) - 1); //-1为'\n'
    //         // ESP_LOGI(TAG_BTN, "siezof=%d", sizeof(img_val));
    //         //重置缓存数组
    //         memset(img_val, '\0', sizeof(img_val)); 
    //
    //         vTaskDelay(1); //for WDT
    //     }
    //
    //     SDCard_File_Close();
    //     ePaper_FullDispaly();
    //
    //     ESP_LOGI(TAG_BTN, "end of set tmp.txt");   
    // }
//
//
//



